import { request } from "./request";

async function listUser() {
  const response = await request("/user", "GET", null, true);
  if (!Array.isArray(response)) {
    throw Error("Invalid response");
  }
  return response;
}

async function updateUser(userId, newInfo) {
  if (typeof newInfo != "object") {
    throw Error("Invalid argument");
  }
  await request(`/user/${userId}`, "PATCH", newInfo, true);
}

async function createUser(userinfo) {
  const response = await request("/user/create", "POST", userinfo, true);
  if (typeof response != "object") {
    throw Error("Invalid response");
  }
  if (typeof response.id != "number") {
    throw Error("Invalid id");
  }
  return response.id;
}

async function deleteUser(id) {
  if (typeof id != "number" || (id != (id | 0))) {
    throw Error("Invalid argument");
  }
  await request(`/user/${id}`, "DELETE", null, true);
}

async function updatePassword(oldPassword, newPassword) {
  await request("/user/password/update", "POST", {
    oldPassword, newPassword
  }, true);
}

export { listUser, createUser, updateUser, deleteUser, updatePassword };